package com.example.forum.exception;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Slf4j
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(ApplicationException.class)
    public AppResult handleApplicationException(ApplicationException e){
        log.error(e.getMessage());

        if(e.getErrorResult() != null){
            //返回异常类中记录的状态
            return e.getErrorResult();
        }
        //，默认返回异常信息
        return AppResult.fail(e.getMessage());
    }
    @ExceptionHandler(Exception.class)
    public AppResult handleException(Exception e){
        log.error(e.getMessage());

        if(e.getMessage() == null){
            return AppResult.fail(ResultCode.ERROR_SERVICES);
        }

        return AppResult.fail(e.getMessage());
    }
}
